import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author YuanYuan
 * @Date 2022/11/28
 * @Time 15:36
 */
@WebServlet("/drop")
public class DropServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession httpSession = req.getSession(false);
        if(null == httpSession) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        User user = (User) httpSession.getAttribute("user");
        if(null == user) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        String blogId = req.getParameter("blogId");
        if(null == blogId) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("错误");
            return;
        }
        Blog blog = null;
        try {
            blog = BlogDAO.selectOne(Integer.parseInt(blogId));
            if(null == blog) {
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("该博客不存在!");
                return;
            }
            if(user.getUserId()!= blog.getUserId()) {
                resp.setStatus(403);
                resp.setContentType("text/html;charset=utf8");
                resp.getWriter().write("该博客不是您的博客!");
                return;
            }
            BlogDAO.delete(blog.getBlogId());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        resp.setStatus(302);
        resp.sendRedirect("blog_list.html");

    }
}
